/*
 * Copyright (C) 2009 Georgios J. Georgopoulos, All rights reserved.
 * 
 * This is free software; you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 3 of the License, or (at your option) any
 * later version.
 * 
 * This software is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with this software; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF
 * site: http://www.fsf.org.
 */
package org.gwt.mosaic.xul.client.ui;

import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

/**
 * 
 * @author georgopoulos.georgios(at)gmail.com
 * 
 */
public class Textbox extends Element {
  private static final long serialVersionUID = 3434309546362160754L;

  private transient TextBox textBox = null;

  // -----------------------------------------------------------------------
  /**
   * Indicates whether the element is disabled or not. If this element is set to
   * true the element is disabled. Disabled elements are usually drawn with
   * grayed-out text. If the element is disabled, it does not respond to user
   * actions, it cannot be focused, and the command event will not fire.
   */
  public static final String DISABLED = "disabled";

  public boolean isDisabled() {
    return getBoolean(DISABLED);
  }

  public void setDisabled(boolean disabled) {
    putBoolean(DISABLED, disabled);
  }

  // -----------------------------------------------------------------------
  /**
   * The default value entered in a textbox.
   */
  public static final String VALUE = "value";

  public String getValue() {
    return getString(VALUE);
  }

  public void setValue(String value) {
    putString(VALUE, value);
  }

  // -----------------------------------------------------------------------
  public Textbox() {
    super();
  }

  @Override
  protected Widget createUI() {
    if (textBox == null) {
      textBox = new TextBox();
      textBox.addChangeHandler(new ChangeHandler() {
        public void onChange(ChangeEvent event) {
          setValue(textBox.getValue());
        }
      });
    }

    syncUI(textBox);

    return textBox;
  }

  // -----------------------------------------------------------------------
  @Override
  protected void syncUI(Widget ui) {
    super.syncUI(ui);

    if (attributeMap.containsKey(VALUE)) {
      textBox.setValue(getValue());
    }

    textBox.setEnabled(!isDisabled());
  }

}
